package com.yanfei.zero.application.handler.secret;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.yanfei.zero.infrastructure.config.DeveloperProperty;

import cn.hutool.crypto.asymmetric.AsymmetricAlgorithm;
import cn.hutool.crypto.asymmetric.AsymmetricCrypto;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
/**
 * 返回数据统一处理
 */
@RestControllerAdvice
@RequiredArgsConstructor
public class EncryptResponse implements ResponseBodyAdvice<Object>  {

	final DeveloperProperty developerProperty;


	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		return returnType.hasMethodAnnotation(Encrypt.class);
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {
		
    	AsymmetricCrypto decrypt = new AsymmetricCrypto(AsymmetricAlgorithm.RSA,developerProperty.getPrivateKey(),developerProperty.getPublicKey());
    	String parm  =  decrypt.encryptBase64(body.toString(), KeyType.PrivateKey);
    	Map<String,Object> rst = new HashMap<>();
    	rst.put("code", HttpStatus.OK.value());
    	rst.put("data", parm);
		return JSONUtil.toJsonPrettyStr(rst);
	}
}
